package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.service.IBankAccountService;
import com.jzo2o.mvc.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 银行账户信息表（服务人员/机构共用） 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-02
 */
@Slf4j
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {

    /**
     * 新增或更新
     *
     * @param dto
     */
    @Override
    public void addOrUpdate(BankAccountUpsertReqDTO dto) {
        //首先先进行健壮性判断
        if (dto == null) {
            throw new CommonException("请输入有效的数据");
        }
        //先查询是否存在
        BankAccount exist = lambdaQuery()
                .eq(BankAccount::getAccount, dto.getAccount())
//                .eq(BankAccount::getBankName, dto.getBankName())
//                .eq(BankAccount::getBranch, dto.getBranch())
//                .eq(BankAccount::getCity, dto.getCity())
//                .eq(BankAccount::getDistrict, dto.getDistrict())
//                .eq(BankAccount::getProvince, dto.getProvince())
                .one();
        if (exist != null) {
            dto.setId(exist.getId());
            BeanUtils.copyProperties(dto, exist);

            //存在则进行更新
            boolean b = updateById(exist);
            if (!b) {
                throw new CommonException("更新银行账户信息失败");
            }
        } else {
            //不存在则进行新增
            BankAccount bankAccount = BeanUtils.copyBean(dto, BankAccount.class);
            bankAccount.setUserId(UserContext.currentUserId());
            bankAccount.setType(2);
            boolean save = save(bankAccount);
            if (!save) {
                throw new CommonException("新增银行账户信息失败");
            }
        }
    }

    /**
     * 查询当前用户银行信息
     *
     * @return
     */
    @Override
    public BankAccount queryBankAccount() {
        //获取当前用户信息
        Long l = UserContext.currentUserId();
        BankAccount bankAccount = lambdaQuery()
                .eq(BankAccount::getUserId, l)
                .one();
        if (bankAccount == null){
//            throw new CommonException("请先添加银行账户信息");
            bankAccount = new BankAccount();
        }
        return bankAccount;
    }
}
